package com.leyou.cart.service;

import com.leyou.cart.client.GoodsClient;
import com.leyou.cart.interceptor.LoginInterceptor;
import com.leyou.cart.pojo.Cart;
import com.leyou.common.pojo.UserInfo;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.pojo.Sku;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @create: 2019-07-20 16:57
 **/
@Service
public class CartService {

    /**
     * redis中购物车字段的前缀
     */
    private static final String KEY_PERFIX = "user:cart:";

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private GoodsClient goodsClient;

    /**
     * 添加商品到购物车，保存到reids中
     *
     * @param cart
     * @return
     */
    public void addCart(Cart cart) {
        //获取用户信息
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        //查询购物车记录，
        BoundHashOperations<String, Object, Object> hashOperations = this.redisTemplate.boundHashOps(KEY_PERFIX + userInfo.getId());

        //skuId
        String skuId = cart.getSkuId().toString();
        //商品数量
        Integer num = cart.getNum();

        //判断当前购物车商品是否已存在
        if (hashOperations.hasKey(skuId)) {
            //已存在，更新数量
            //获取商品的json字符串
            String cartJson = hashOperations.get(skuId).toString();
            //使用工具类转换成cart对象
            cart = JsonUtils.parse(cartJson, Cart.class);
            //更新数量
            cart.setNum(cart.getNum() + num);
        } else {
            //未存在，新增商品
            //获取sku对象
            Sku sku = this.goodsClient.querySkuById(cart.getSkuId());
            //完善商品信息
            cart.setUserId(userInfo.getId());
            cart.setTitle(sku.getTitle());
            cart.setOwnSpec(sku.getOwnSpec());
            cart.setImage(StringUtils.isBlank(sku.getImages()) ? "" : StringUtils.split(sku.getImages(), ",")[0]);
            cart.setPrice(sku.getPrice());
        }
        //将新的商品信息序列化成json字符串更新到reids
        hashOperations.put(skuId, JsonUtils.serialize(cart));
    }

    /**
     * 获取用户的购物车信息
     *
     * @return
     */
    public List<Cart> queryCarts() {
        //获取用户
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        //判断用户是否有购物车信息
        if (!redisTemplate.hasKey(KEY_PERFIX + userInfo.getId())) {
            return null;
        }

        //从redis中获取用户的购物车
        BoundHashOperations<String, Object, Object> hashOperations = redisTemplate.boundHashOps(KEY_PERFIX + userInfo.getId());
        //获取所有值的集合
        List<Object> cartsJson = hashOperations.values();

        //判断购物车内是否有商品
        if (CollectionUtils.isEmpty(cartsJson)) {
            return null;
        }

        //将集合内的值通过json反序列化成cart对象,并返回
        return cartsJson.stream().map(cartJson -> {
            return JsonUtils.parse(cartJson.toString(), Cart.class);
        }).collect(Collectors.toList());
    }

    /**
     * 修改购物车商品数量
     *
     * @param cart
     * @return
     */
    public void updateNum(Cart cart) {
        //获取用户
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        //判断用户是否有购物车信息
        if (!redisTemplate.hasKey(KEY_PERFIX + userInfo.getId())) {
            return;
        }

        //从redis中获取用户的购物车
        BoundHashOperations<String, Object, Object> hashOperations = redisTemplate.boundHashOps(KEY_PERFIX + userInfo.getId());
        //获取商品
        String cartJson = hashOperations.get(cart.getSkuId().toString()).toString();
        //修改后的数量
        Integer num = cart.getNum();
        //转换
        cart = JsonUtils.parse(cartJson, Cart.class);
        cart.setNum(num);

        //重新保存，注意保存的对象要json序列化
        hashOperations.put(cart.getSkuId().toString(), JsonUtils.serialize(cart));
    }

    /**
     * 删除购物车内的商品
     *
     * @param cart
     * @return
     */
    public void deleteCart(Cart cart) {
        //获取用户
        UserInfo userInfo = LoginInterceptor.getUserInfo();

        //判断用户是否有购物车信息
        if (!redisTemplate.hasKey(KEY_PERFIX + userInfo.getId())) {
            return;
        }

        //从redis中获取用户的购物车
        BoundHashOperations<String, Object, Object> hashOperations = redisTemplate.boundHashOps(KEY_PERFIX + userInfo.getId());
        //判断商品是否存在
        if (!hashOperations.hasKey(cart.getSkuId().toString())) {
            return;
        }
        //删除商品
        hashOperations.delete(cart.getSkuId().toString());
    }
}
